package com.angel.web.health;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.angel.core.util.FastDFSClient;
import com.angel.core.util.JsonUtil;

/**
 * 高亚林
 * 2016年9月23日下午7:38:58
 */

@Controller
@RequestMapping("/pic")
public class PicController {

	@RequestMapping("/uploadFile")
	@ResponseBody
	public Map<String, Object> uploadFile(@RequestParam(value = "uploadfile", required = false) MultipartFile uploadfile) throws IOException, Exception{
		
		Map<String, Object> map = new HashMap<>();
		
		FastDFSClient client = new FastDFSClient();
		
		String path = null;
		
		if(uploadfile != null){
			String originalFilename = uploadfile.getOriginalFilename();
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
			path = client.uploadFile(uploadfile.getBytes(), extName);			
		}
		
		map.put("path", path);
		map.put("status", "success");
		map.put("msg", "上传成功！");
			
		return map;
	}
	
	@RequestMapping("/uploadCutImage")
	@ResponseBody
	public Map<String, Object> uploadCutImage(@RequestParam(value = "uploadfile", required = false) MultipartFile uploadfile, String avatarData) throws IOException, Exception{
		
		Map<String, Object> dataMap = JsonUtil.jsonToMap(avatarData);
		
		Map<String, Object> map = new HashMap<>();
		
		FastDFSClient client = new FastDFSClient();
		
		String originalFilename = uploadfile.getOriginalFilename();
		String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
		
		BufferedImage img = ImageIO.read(uploadfile.getInputStream());
		
		int x = Double.valueOf(String.valueOf(dataMap.get("x"))).intValue();
		int y = Double.valueOf(String.valueOf(dataMap.get("y"))).intValue();
		int width = Double.valueOf(String.valueOf(dataMap.get("width"))).intValue();
		int height = Double.valueOf(String.valueOf(dataMap.get("height"))).intValue();
			
		img = img.getSubimage(x, y, width, height);
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(img, extName, bos);
		
		String path = client.uploadFile(bos.toByteArray(), extName);
		
		map.put("path", path);
		map.put("status", "success");
		map.put("msg", "上传成功！");
			
		return map;
	}
}






